package utils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
)

func pkcs7Padding(data []byte, blockSize int) []byte {
	padding := blockSize - len(data)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(data, padText...)
}

func pkcs7UnPadding(data []byte) []byte {
	length := len(data)
	unPadding := int(data[length-1])
	return data[:(length - unPadding)]
}

func encryptAES(data []byte, key []byte) []byte {
	block, err := aes.NewCipher(key)
	Must(err)
	blockSize := block.BlockSize()
	encryptBytes := pkcs7Padding(data, blockSize)
	crypted := make([]byte, len(encryptBytes))
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	blockMode.CryptBlocks(crypted, encryptBytes)
	return crypted
}

func decryptAES(data []byte, key []byte) []byte {
	block, err := aes.NewCipher(key)
	Must(err)
	blockSize := block.BlockSize()
	crypted := make([]byte, len(data))
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	blockMode.CryptBlocks(crypted, data)
	crypted = pkcs7UnPadding(crypted)
	return crypted
}

func EncryptByAES(data []byte, key []byte) string {
	res := encryptAES(data, key)
	return base64.StdEncoding.EncodeToString(res)
}

func DecryptByAES(data string, key []byte) []byte {
	dataByte, err := base64.StdEncoding.DecodeString(data)
	Must(err)
	return decryptAES(dataByte, key)
}
